package com.amos.muexamclient.async;

import com.amos.muexamcore.util.SpringUtils;

import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Copyright © 2018 五月工作室. All rights reserved.
 *
 * @Package com.amos.muexamclient.async
 * @ClassName AsyncManager
 * @Description 异步任务管理
 * @Author Amos
 * @Modifier
 * @Date 2020/3/21 22:25
 * @Version 1.0
 **/
public class AsyncManager {

    /**
     * 操作延迟10毫秒
     */
    private static final int OPERATE_DELAY_TIME = 10;
    /**
     * 异步操作任务调度线程池
     */
    private ScheduledExecutorService executor = SpringUtils.getBean("scheduledExecutorService");
    /**
     * 构造器私有化，防止创建实例对象
     */
    private AsyncManager(){

    }

    /**
     * 私有化静态内部类，在静态内部类被调用时去实例化对象
     */
    private static class Singleton{
        private static AsyncManager asyncManager;

        static {
            asyncManager = new AsyncManager();
        }
        private static  AsyncManager getInstance(){
            return asyncManager;
        }
    }

    /**
     * 对外提供获取AsyncManager的实例对象，并且确保对象单一
     * @return
     */
    public static AsyncManager getInstance() {
        return AsyncManager.Singleton.getInstance();
    }

    /**
     * 执行定时任务
     * @param task
     */
    public void execute(TimerTask task) {
        AsyncManager.getInstance().executor.schedule(task,AsyncManager.OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
    }

    /**
     * 关闭
     */
    public void close() {
        ThreadUtils.shutdownAndAwaitTermination(executor);
    }

}
